<?php

namespace Beike\Repositories;

use Beike\Models\ProductSku;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;

class ProductSkusRep{

    /**
     * 获取所有商品列表
     *
     * @param array $filters
     * @return Builder[]|Collection
     */
    public static function filterAll(array $filters = [])
    {
        $builder = static::getListBuilder($filters)->orderByDesc('ps.created_at');
        return $builder->get();
    }

    /**
     * @param array $filters
     * @return Builder
     */
    public static function getListBuilder(array $filters = []): Builder
    {
        $builder = ProductSku::query()->with(['product']);
        $builder->from('product_skus as ps');
        $builder->leftJoin('products as p', 'p.id', '=', 'ps.product_id');
        $builder->leftJoin('product_descriptions as pd', function ($build) {
            $build->whereColumn('pd.product_id', 'ps.product_id')->where('pd.locale', locale());
        });
        $builder->select('ps.*');

        if (isset($filters['category_id'])) {
            $builder->leftJoin('product_categories as pc', function ($build) {
                $build->whereColumn('pc.product_id', 'ps.product_id');
            });
            if (is_array($filters['category_id'])) {
                $builder->whereIn('pc.category_id', $filters['category_id']);
            } else {
                $builder->where('pc.category_id', $filters['category_id']);
            }
        }

        if (isset($filters['name'])) {
            $builder->where('pd.name', 'like', "%{$filters['name']}%");
        }
        if (isset($filters['sku'])) {
            $builder->where('ps.sku', 'like', "%{$filters['sku']}%");
        }
        if (isset($filters['model'])) {
            $builder->where('ps.model', 'like', "%{$filters['model']}%");
        }

        if (isset($filters['active'])) {
            $builder->where('p.active', (int) $filters['active']);
        }

        return $builder;
    }
}
